package com.my.basics.demo.demo01;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

/**
 * @author mars
 * @date 2025-04-11 16:07
 */
public class HelloNettyClient {
    private final String host;
    private final int port;

    public HelloNettyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() {
        try (
                // NioEventLoopGroup is a multithreaded event loop that handles I/O operation
                var group = new NioEventLoopGroup()
        )
        {
            var bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class) // set channel type
                    .remoteAddress(new InetSocketAddress(host, port))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new HelloNettyClientHandler());
                        }
                    });
            // connect to server
            ChannelFuture future = bootstrap.connect().syncUninterruptibly();
            // send msg to server
            future.channel().writeAndFlush(Unpooled.copiedBuffer("Hello, this is client, please reply", CharsetUtil.UTF_8));
            // close
            future.channel().closeFuture().syncUninterruptibly();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new HelloNettyClient("127.0.0.1", 8099).start();
    }
}
